package com.vdong.supplier.util;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 单独Object 自定义，非全局
 *
 * @author liangwei
 */
public enum ObjectMapperSingleton {

    ObjectMapperCustom;
    private ObjectMapper jsonObjectMap;

    /**
     * 单例首字母大写，locationDateTime格式化时间戳
     */
    ObjectMapperSingleton() {
        jsonObjectMap = new ObjectMapper();

        jsonObjectMap.setPropertyNamingStrategy(new PropertyNamingStrategy() {
            private static final long serialVersionUID = 1L;

            // 反序列化时调用 首字母大写的json
            @Override
            public String nameForSetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
                return method.getName().substring(3);
            }
            /*
             * // 序列化时调用
             *
             * @Override public String nameForGetterMethod(MapperConfig<?> config,
             * AnnotatedMethod method, String defaultName) { return
             * method.getName().substring(3); }
             */
        });

        jsonObjectMap.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        jsonObjectMap.setSerializationInclusion(Include.NON_NULL);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTimeSerializer serializer = new LocalDateTimeSerializer(formatter);
        LocalDateTimeDeserializer deserializer = new LocalDateTimeDeserializer(formatter);
        jsonObjectMap.registerModule(new JavaTimeModule().addSerializer(LocalDateTime.class, serializer)
                .addDeserializer(LocalDateTime.class, deserializer));

    }

    public ObjectMapper getJsonObjectMap() {
        return jsonObjectMap;
    }

}
